package com.yiyi.handler;

import com.alibaba.fastjson.JSONObject;
import com.yiyi.config.JwtConfigProperties;
import com.yiyi.util.JWTUtil;
import com.yiyi.util.ResponseUtil;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


/**
 * User: YIYI
 * Date: 2021-08-10
 * Time: 15:14
 * Description:
 */

@Slf4j
@Component
public class AuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {

    @Autowired
    private JwtConfigProperties jwtConfigProperties;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {

        List<String> authorities=((UserDetails) authentication.getPrincipal()).getAuthorities().stream().map(a->new String(((GrantedAuthority) a).getAuthority())).collect(Collectors.toList());
        String username = ((UserDetails) authentication.getPrincipal()).getUsername();
        //登陆成功生成token
        String token = JWTUtil.sign(username,jwtConfigProperties,authorities);
//        String token = Jwts.builder()
//                //主题 放入用户名
//                .setSubject(username)
//                //自定义属性 放入用户拥有请求权限
//                .claim("authorities",JSONObject.toJSONString(authorities))
//                //失效时间
//                .setExpiration(new Date(System.currentTimeMillis() + 7 * 60 * 1000))
//                //签名算法和密钥
//                .signWith(SignatureAlgorithm.HS512, jwtConfigProperties.getSecret())
//                .compact();
        //token 需要保存至服务器一份，实现方式：redis or jwt  输出到浏览器
        ResponseUtil.out(response, ResponseUtil.resultMap(true, 200, token));
    }
}
